using System;
using System.Data;
using System.Data.SqlClient;
using System.Collections.Generic;
using System.Text;
using System.Collections;
namespace SSG {
	public class DatabaseUtilities {
		public static string StatsStr;
		public static DataTable GetDatabases(string sConnection) {
			string query="SELECT name FROM master.dbo.sysdatabases WHERE HAS_DBACCESS(name)=1 order by 1";
			DataTable dt=LoadDataTable(sConnection,null,query);
			return dt;
		}
		public static DataTable GetTables(string sConnection,string sDatabase) {
			string sql=@"select distinct table_name,table_schema+'.'+table_name[val] from information_schema.tables where table_type='BASE TABLE'"+Settings.Hide;
			return LoadDataTable(sConnection,sDatabase,sql);
		}
		public static DataTable LoadDataTable(string sConnection,string sDatabase,string sQuery) {
			DataTable ret=new DataTable();
			string db="";
			if(sDatabase!=null)
				db="database="+sDatabase;
			if(!sConnection.EndsWith(";"))
				sConnection+=";";
			using(SqlConnection con=new SqlConnection(sConnection+db))
			using(SqlCommand cmd=new SqlCommand(sQuery+Settings.Hide,con))
			{
				cmd.CommandTimeout=int.Parse(Settings.Timeout);
				con.StatisticsEnabled=true;
				con.Open();
				//if(sDatabase!=null)
				//  con.ChangeDatabase(sDatabase);
				using(SqlDataAdapter da=new SqlDataAdapter(cmd))
					da.Fill(ret);




				List<string> lst=new List<string>(18);
				foreach(DictionaryEntry var in con.RetrieveStatistics())
					lst.Add(var.Key.ToString()+": "+var.Value.ToString());
				StatsStr=string.Join(Environment.NewLine,lst.ToArray());

			}
			return ret;
		}

		public static string GetIdentityColumnName(string cs,string tableSep) {
			SqlConnection sqlConnection=new SqlConnection(cs);
			string commandString=string.Format(@"select COLUMN_NAME from INFORMATION_SCHEMA.COLUMNS 
where TABLE_SCHEMA = 'dbo' and COLUMNPROPERTY(object_id(TABLE_NAME), COLUMN_NAME, 'IsIdentity') = 1 
and TABLE_NAME='{0}' order by TABLE_NAME",tableSep);
			DataTable tab=new DataTable();
			SqlDataAdapter sqlDataAdapter=new SqlDataAdapter();
			sqlDataAdapter.SelectCommand=new SqlCommand(commandString,sqlConnection);
			sqlDataAdapter.Fill(tab);

			if(tab.Rows.Count>0)
			{
				return tab.Rows[0][0].ToString();
			}
			return "";
		}
	}
}
